package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.model.request.BankerProductSpecRequest;
import com.ytjj.qmyx.supplychain.common.model.request.UpdateSkuRequest;
import com.ytjj.qmyx.supplychain.common.model.response.ProductSkuKeyResponse;
import com.ytjj.qmyx.supplychain.common.model.response.ProductSpecResponse;
import com.ytjj.qmyx.supplychain.mapper.BankerProductSkuKeyMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerProductSkuValueMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerProductSpecMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
public class BankerProductSpecService extends AbstractService<BankerProductSpecMapper, YxBankerProductSpec> {
    @Resource
    private BankerProductSpecMapper bankerProductSpecMapper;
    @Resource
    private BankerProductSkuKeyMapper bankerProductSkuKeyMapper;
    @Resource
    private BankerProductSkuValueMapper bankerProductSkuValueMapper;
    @Autowired
    private BankerService bankerService;

    @Transactional(rollbackFor = Exception.class)
    public void updateBankerProductSpecStock(Integer id, Integer stock) {
        YxBankerProductSpec yxBankerProductSpec = new YxBankerProductSpec();
        yxBankerProductSpec.setStock(stock);
        yxBankerProductSpec.setId(id);
        bankerProductSpecMapper.updateByPrimaryKeySelective(yxBankerProductSpec);
    }

    public void updateProductSpecPrice(Integer id, BigDecimal price, BigDecimal salePrice) {
        YxBanker userInfo = bankerService.getUserInfo();
        YxBankerProductSpec yxBankerProductSpec = new YxBankerProductSpec();
        yxBankerProductSpec.setId(id);
        yxBankerProductSpec.setBankerId(userInfo.getId());
        yxBankerProductSpec.setPrice(price);
        yxBankerProductSpec.setSalePrice(salePrice);
        yxBankerProductSpec.setUpdateTime(new Date());
        bankerProductSpecMapper.updateByPrimaryKeySelective(yxBankerProductSpec);
    }

    public void updateSpecImg(Integer id, String imgUrl) {
        YxBankerProductSpec yxBankerProductSpec = new YxBankerProductSpec();
        yxBankerProductSpec.setId(id);
        yxBankerProductSpec.setProImg(imgUrl);
        yxBankerProductSpec.setUpdateTime(new Date());
        bankerProductSpecMapper.updateByPrimaryKeySelective(yxBankerProductSpec);
    }

    public CommonPage<YxBankerProductSpec> getBankerProductSpec(BankerProductSpecRequest bankerProductSpecRequest) {
        Example example = new Example(YxBankerProductSpec.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != bankerProductSpecRequest.getProductId()) {
            criteria.andEqualTo("productId", bankerProductSpecRequest.getProductId());
        }
        if (null != bankerProductSpecRequest.getBankerId()) {
            criteria.andEqualTo("bankerId", bankerProductSpecRequest.getBankerId());
        }
        if (!StringUtils.isEmpty(bankerProductSpecRequest.getSkuSpec())) {
            criteria.andEqualTo("skuSpec", bankerProductSpecRequest.getSkuSpec());
        }
        example.orderBy("createTime").desc();
        PageHelper.startPage(bankerProductSpecRequest.getPageNum(), bankerProductSpecRequest.getPageSize());
        List<YxBankerProductSpec> bankerProductSpecList = bankerProductSpecMapper.selectByExample(example);
        return CommonPage.restPage(bankerProductSpecList);
    }

    public List<YxBankerProductSpec> getBankerProductSpecList(BankerProductSpecRequest bankerProductSpecRequest) {
        Example example = new Example(YxBankerProductSpec.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != bankerProductSpecRequest.getProductId()) {
            criteria.andEqualTo("productId", bankerProductSpecRequest.getProductId());
        }
        if (null != bankerProductSpecRequest.getBankerId()) {
            criteria.andEqualTo("bankerId", bankerProductSpecRequest.getBankerId());
        }
        if (!StringUtils.isEmpty(bankerProductSpecRequest.getSkuSpec())) {
            criteria.andEqualTo("skuSpec", bankerProductSpecRequest.getSkuSpec());
        }
        example.orderBy("createTime").desc();
        List<YxBankerProductSpec> bankerProductSpecList = bankerProductSpecMapper.selectByExample(example);
        return bankerProductSpecList;
    }

    public List<YxBankerProductSpec> getBankerProductSpecListByBankerIdAndProductId(Integer bankerId, Integer productId) {
        Example example = new Example(YxBankerProductSpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", 1);
        if (null != bankerId) {
            criteria.andEqualTo("bankerId", bankerId);
        }
        if (null != productId) {
            criteria.andEqualTo("productId", productId);
        }
        List<YxBankerProductSpec> list = bankerProductSpecMapper.selectByExample(example);
        return list;
    }

    public Integer updateMoreSalePrice(Integer[] specIds, BigDecimal salePrice) {
        Example example = new Example(YxBankerProductSpec.class);
        example.createCriteria().andIn("id", Arrays.asList(specIds));
        List<YxBankerProductSpec> list = bankerProductSpecMapper.selectByExample(example);
        AtomicReference<Integer> count = new AtomicReference<>(0);
        list.stream().forEach(item -> {
            item.setSalePrice(salePrice);
            count.updateAndGet(v -> v + bankerProductSpecMapper.updateByPrimaryKey(item));
        });

        return count.get();
    }

    public void updateProductSpec(UpdateSkuRequest updateSkuRequest) {
        List<ProductSpecResponse> NewSpecs = updateSkuRequest.getSpec();
        Example example = new Example(YxBankerProductSpec.class);
        example.createCriteria().andEqualTo("bankerId", updateSkuRequest.getBankerId()).andEqualTo("productId", updateSkuRequest.getProductId());
        List<YxBankerProductSpec> OldSpecs = bankerProductSpecMapper.selectByExample(example);
        //先删一遍
        isDel(updateSkuRequest.getProductId());
        //把旧的规格建议售价替代到新的规格
        for (ProductSpecResponse NewSpec : NewSpecs) {
            for (YxBankerProductSpec oldSpec : OldSpecs) {
                if (NewSpec.getSkuSpec().equals(oldSpec.getSkuSpec())) {
                    NewSpec.setSalePrice(oldSpec.getSalePrice());
                }
            }
        }
        //再重新保存一遍
        saveProductSpecAndSku(updateSkuRequest);
    }

    public void isDel(Integer productId) {
        Example example1 = new Example(YxBankerProductSkuKey.class);
        example1.createCriteria().andEqualTo("pid", productId);
        bankerProductSkuKeyMapper.deleteByExample(example1);

        Example example2 = new Example(YxBankerProductSkuValue.class);
        example2.createCriteria().andEqualTo("pid", productId);
        bankerProductSkuValueMapper.deleteByExample(example2);

        Example example3 = new Example(YxBankerProductSpec.class);
        example3.createCriteria().andEqualTo("productId", productId);
        bankerProductSpecMapper.deleteByExample(example3);
    }

    public void saveProductSpecAndSku(UpdateSkuRequest updateSkuRequest) {
        List<ProductSpecResponse> specs = updateSkuRequest.getSpec();
        specs.stream().forEach(item -> {
            YxBankerProductSpec productSpec = new YxBankerProductSpec();
            productSpec.setBankerId(updateSkuRequest.getBankerId());
            productSpec.setProductId(updateSkuRequest.getProductId());
            productSpec.setSkuSpec(item.getSkuSpec());
            productSpec.setPrice(item.getCostPrice());
            productSpec.setSalePrice(item.getSalePrice());
            productSpec.setProImg(item.getProImg());
            productSpec.setStock(item.getStock());
            productSpec.setCreateTime(item.getCreateTime());
            productSpec.setUpdateTime(item.getUpdateTime());
            productSpec.setOriginalPrice(item.getOriginalPrice());
            productSpec.setThreeSkuId(item.getThreeSkuId());
            bankerProductSpecMapper.insert(productSpec);
        });
        List<ProductSkuKeyResponse> skuKey = updateSkuRequest.getSkuKey();
        for (ProductSkuKeyResponse productSkuKeyRequest : skuKey) {
            productSkuKeyRequest.setPid(updateSkuRequest.getProductId());
            YxBankerProductSkuKey productSkuKey = new YxBankerProductSkuKey();
            productSkuKey.setPid(productSkuKeyRequest.getPid());
            productSkuKey.setName(productSkuKeyRequest.getName());
            productSkuKey.setSort(productSkuKeyRequest.getSort());
            productSkuKey.setCreateTime(new Date());
            bankerProductSkuKeyMapper.insert(productSkuKey);

            productSkuKeyRequest.getSkuValue().stream().forEach(item -> {
                YxBankerProductSkuValue productSkuValue = new YxBankerProductSkuValue();
                productSkuValue.setPid(updateSkuRequest.getProductId());
                productSkuValue.setKid(productSkuKeyRequest.getId());
                productSkuValue.setValue(item.getValue());
                productSkuValue.setCreateTime(new Date());
                productSkuValue.setStatus(new Byte("1"));
                bankerProductSkuValueMapper.insert(productSkuValue);
            });
        }
    }
}
